<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\LibApi\CqLibApiSip2Controller;
use App\Http\Controllers\LibApi\CqstLibController;
use App\Http\Controllers\LibApi\YzqLibApiController;
use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\ScoreRuleController;
use App\Models\BindLog;
use App\Models\BookTypes;
use App\Models\UserInfo;
use App\Validate\LibInfoValidate;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 图书馆对接接口信息
 */
class LibInfoController extends CommonController
{
    public $libapiObj = null;
    public $validate = null;
    public function __construct()
    {
        parent::__construct();

        $this->validate = new LibInfoValidate();
        $this->libapiObj = new YzqLibApiController();
    }


    /**
     * 绑定读者证  或密码错误重新登录
     * @param $authorrization ：用户 token
     * @param account 读者证号
     * @param password 读者证密码
     * @param lib_id 图书馆id  1 为渝中区本馆  2 重庆市一卡通成员馆
     */
    public function bingReaderId()
    {
        //  return $this->returnApi(201, '功能正在开发中...');

        $account = $this->request->account;
        $password = $this->request->password;
        $user_id = $this->request->user_info['id'];

        //增加验证场景进行验证
        if (!$this->validate->scene('bing_reader')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否绑定了读者证
        $userInfoModel = new UserInfo();
        $user_info = $userInfoModel->where('id', $user_id)->first();
        //因为可能是密码错误。这个不判断
        // if (!empty($user_info['account_id'])) {
        //     return $this->returnApi(202, "您已绑定其他读者证，请勿重复绑定");
        // }

        if ($this->request->lib_id == 2) {
            $cqLibSip2 = new CqLibApiSip2Controller();
            $res = $cqLibSip2->getRFeaderInfo($account, $password);
        } else {
            $libapiObj = new YzqLibApiController();
            $res = $libapiObj->login($account, $password);
        }

        if ($res['code'] === 200) {
            //登录成功
            DB::beginTransaction();
            try {
                $res['content']['lib_id'] = $this->request->lib_id;
                if ($this->request->lib_id == 2) {
                    $account = $res['content']['reader_id']; //重新赋值账号，因为有可能是身份证登录的            
                } else {
                    $account = $res['content']['cardno']; //重新赋值账号，因为有可能是身份证登录的
                }
                //判断此证号是否第一次绑定
                $userLibraryInfoModel = new UserLibraryInfo();
                $result = $userLibraryInfoModel->where('account', $account)->first();
                $first_bind = $result; //用这个判断是否已经绑定过

                if ($result) {
                    //判断此读者证是否被其他用户绑定
                    $isBindAccount = $userLibraryInfoModel->isBindAccount($result->id, $user_id);
                    if ($isBindAccount !== true) {
                        throw new \Exception($isBindAccount, 2002);
                    }

                    $res['content']['password'] = $password;
                    $qr_url = $userLibraryInfoModel->change($res['content'], $result);
                    $account_id = $result->id;
                } else {
                    $res['content']['password'] = $password;
                    $qr_url = $userLibraryInfoModel->change($res['content']);
                    $account_id = $userLibraryInfoModel->id;
                }

                //绑定在用户信息里面
                if (empty($user_info['account_id'])) {
                    //判断是否有积分，如果有积分，同步在读者证上，之前遗留数据
                    $user_info_score = $userInfoModel->where('id', $user_id)->value('score');
                    //修改读者证号二维码
                    $userInfoModel->where('id', $user_id)->update([
                        'account_id' => $account_id,
                        // 'qr_url' => $qr_url,//这里是推广二维码
                        'score' => 0,
                        'bind_time' => date('Y-m-d H:i:s')
                    ]);

                    if ($user_info_score) {
                        //积分同步,增加积分
                        $userLibraryInfoModel->where('id', $account_id)->increment('score', $user_info_score);
                    }

                    //添加绑定日志
                    $bindLogModel = new BindLog();
                    $bindLogModel->add([
                        'user_id' => $user_id,
                        'account' => $account,
                        'password' => $password,
                        'state' => 1,
                    ]);
                } elseif ($user_info['account_id'] != $account_id) {
                    throw new Exception('您已绑定其他读者证号，请勿重复绑定', 2002);
                }

                //是否第一次绑定读者证
                // if (config('other.is_need_score') === true && empty($first_bind)) {
                //     $scoreRuleObj = new ScoreRuleController();
                //     $score_status = $scoreRuleObj->checkScoreStatus(1, $account_id, false);
                //     if ($score_status['code'] == 200) {
                //         $system_id = $this->systemAdd($score_status['score_info']['type_name'], $user_id, $account_id, 32, 0, $score_status['score_info']['intro']);
                //         $scoreRuleObj->scoreChange($score_status, $account_id, $system_id); //添加积分消息
                //     }

                //     $invite_user_info = $userInfoModel->where('id', $user_id)->first();
                //     //增加邀请人的积分
                //     if (!empty($invite_user_info['invite_user_id']) || !empty($invite_user_info['invite_account_id'])) {
                //         $invite_account_id = $invite_user_info['invite_account_id'];
                //         //从新获取读者证id
                //         if (empty($invite_account_id)) {
                //             $invite_account_id = $userInfoModel->where('id', $invite_user_info['invite_user_id'])->value('account_id');
                //         }
                //         if (!empty($invite_account_id)) {
                //             $score_status = $scoreRuleObj->checkScoreStatus(3, $account_id);

                //             if ($score_status['code'] == 200) {
                //                 $system_id = $this->systemAdd($score_status['score_info']['type_name'], $invite_user_info['invite_user_id'], $invite_user_info['invite_account_id'], 32, 0, $score_status['score_info']['intro']);
                //                 $scoreRuleObj->scoreChange($score_status, $invite_user_info['invite_account_id'], $system_id); //添加积分消息
                //             }
                //         }
                //     }
                // }

                DB::commit();
                return $this->returnApi(200, '绑定成功', true, [
                    'account' => $account,
                    'username' => !empty($res['content']['username']) ? $res['content']['username'] : $res['content']['realName']
                ]);
            } catch (\Exception $e) {
                Log::error($e->getMessage() . $e->getFile() . $e->getLine());
                $msg = $e->getCode() == 2002 ? $e->getMessage() : '绑定失败';
                DB::rollBack();
                return $this->returnApi(202, $msg);
            }
        } else {
            return $this->returnApi(202, $res['msg'] ? $res['msg']  : "登录失败,读者证号或密码不正确");
        }
    }

    /**
     * 解除绑定读者证
     * @param @param $authorrization ：用户 token
     */
    public function unBindReaderId()
    {
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $res = UserInfo::find($user_id);
        if (empty($res)) {
            return $this->returnApi(202, '信息获取失败');
        }
        if (empty($res['account_id'])) {
            return $this->returnApi(202, '网络错误');
        }

        DB::beginTransaction();
        try {
            $res->account_id = null;
            //  $res->qr_url = null;
            $res->bind_time = date('Y-m-d H:i:s');
            $res->save();

            BindLog::where('user_id', $user_id)->where('state', 1)->update(['state' => 2, 'change_time' => date('Y-m-d H:i:s')]);

            //修改掉之前的二维码
            // if ($res->qr_url) {
            //     @unlink(config('other.img_addr') . $res->qr_url);
            // }

            DB::commit();
            return $this->returnApi(200, '解除绑定成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '解除绑定失败');
        }
    }

    /**
     * 修改读者证密码
     * @param $account_id  读者证号 id
     * @param $old_password  读者旧密码
     * @param $new_password  读者新密码
     */
    public function changePwd()
    {
        $user_account_id = $this->request->user_info['account_id'];

        $account_id = request()->account_id;
        $old_password = request()->old_password;
        $new_password = request()->new_password;
        if (empty($account_id) || empty($old_password) || empty($new_password) || $user_account_id != $account_id) {
            return $this->returnApi(201, "参数错误");
        }

        $account_info = UserLibraryInfo::select('id', 'account')->find($account_id);
        if (empty($account_info)) {
            return $this->returnApi(201, "网错错误");
        }
        //验证旧密码是否正确,验证通过后修改密码
        $res = $this->libapiObj->updateReaderPassword($account_info->account, $old_password, $new_password);

        if ($res['code'] === 200) {
            return $this->returnApi(200, "修改成功", true);
        } else {
            return $this->returnApi(202, $res['msg']);
        }
    }


    /**
     * 获取借阅记录列表
     * @param $authorrization 用户 token    例：Bearer 1可选
     * @param type int 1 当前借阅  2 历史借阅记录
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time 借阅开始日期   当前借阅  不需要此参数
     * @param end_time 借阅结束日期    当前借阅  不需要此参数
     */
    public function getBorrowList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_borrow_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $account_id = $this->request->user_info['account_id'];
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        $userLibraryInfoModel = new UserLibraryInfo();
        $user_lib_info = $userLibraryInfoModel->where('id', $account_id)->first();

        if (empty($user_lib_info)) {
            return $this->returnApi(201, '参数错误');
        }
        if ($this->request->type == 1) {
            $res = $this->libapiObj->getNowBorrowList($user_lib_info->account, $page, $limit);
        } else {
            $res = $this->libapiObj->getReturnData($user_lib_info->account, $page, $limit, null, $start_time, $end_time);
        }

        if ($res['code'] == 200) {
            return $this->returnApi(200, '获取成功', true, $res['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取检索信息列表
     * @param keywords_type string 检索类型 all 任意词
     *                              title 书名
                                   author 作者
                                   classno 分类号
                                   isbn isbn号
                                   callno 索书号
     * @param keywords string 检索信息
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function getBookInfoList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('search_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $res = $this->libapiObj->getBookInfo($keywords, "id", "desc", $page, $limit, [$keywords_type]);

        if ($res['code'] == 200) {
            return $this->returnApi(200, '获取成功', true, $res['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取馆藏书籍详情
     * @param metaid 图书在图书馆的id
     * @param metatable 书目库
     */
    public  function getLibBookDetail()
    {
        /*  $a = self::$param;
          //将数组编程字符串的样式
          $aString = '$a = '.var_export($a, true).';';
          //写入文件
          file_put_contents(__DIR__.'/a'.date('ymdhis').'.txt', $aString);*/


        //增加验证场景进行验证
        if (!$this->validate->scene('lib_book_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }


        $metaid = $this->request->metaid;
        $metatable = $this->request->metatable;
        $book_info = $this->libapiObj->getBookDetail($metatable, $metaid);


        $bar_code_info = $this->libapiObj->getAssetPageInfoForOpac($metatable, $metaid);
        //  dump($bar_code_info);
        //  dump($book_info);die;
        if ($book_info['code'] == 200) {
            if (!empty($book_info['classno'])) {
                $classify = substr($book_info['classno'], 0, 1);
                $type_name = BookTypes::where('classify', $classify)->value('title');
                $book_info['content']['type_name'] = $type_name ? $type_name : '暂无分类';
            } else {
                $book_info['content']['type_name'] = '暂无分类';
            }

            //默认接口是不返回封面的
            $book_info['content']['img'] = '/default/default_book.png';
            $book_info['content']['bar_code_info'] = $bar_code_info['content'];

            return $this->returnApi(200, '获取成功', true, $book_info['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }



    /**
     * 在线续借
     * @param token string 用户token
     * @param lib_id 图书馆id
     * @param content json  格式数据 [{"book_name":1,"barcode":11,"author":1},{"book_name":1,"barcode":11,"author":1}]
     *                      数组格式 [['book_name'=>1,'barcode'=>11,'author'=>1],['book_name'=>1,'barcode'=>11,'author'=>1]]
     */
    public function renewBook()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('renew')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->content;

        $content = json_decode($content, true);

        $msg = '';
        foreach ($content as $key => $val) {
            $res = $this->libapiObj->renewBook($val['barcode']);

            $msg .= '【' . $val['book_name'] . '】' . $res['msg'] . '；'; //$res['msg'] 自带一个分号
        }
        return $this->returnApi(200, $msg, true);
    }
}
